package com.code.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token= (String) request.getSession().getAttribute("token");

        ValueOperations ops = redisTemplate.opsForValue();
        String user = null ;
        if(token != null){
             user = (String) ops.get(token);
             request.getSession().setAttribute("token",token);
        }else{
            if (user==null || "".equals(user)){
                response.setContentType("text/html;charset=utf-8");
                StringBuffer url = request.getRequestURL();
                String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getServletContext().getContextPath()).append("/login/to/toLoginIndex").toString();
                log.info(tempContextUrl);
                //String encodedRedirectURL = response.encodeRedirectURL(tempContextUrl);
                response.sendRedirect(tempContextUrl);
                return true;
            }
        }
        return true;
    }



}
